#include "bmserver.h"
#include "ui_bmserver.h"
#include "newbook.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTime>
#include <QDesktopWidget>
#include <QFileInfo>

BMserver::BMserver(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::BMserver)
{
    ui->setupUi(this);

    tableviewPopMenu = new QMenu(ui->tableView);
    //tableviewPopMenu = new QMenu(ui->tableView);
    action_delete = new QAction("Delete It",this);
    action_modify = new QAction("Modify It",this);
    action_copyIt = new QAction("Copy Item",this);

    connect(action_delete,&QAction::triggered,this,&BMserver::deleteItemAction);
    connect(action_modify,&QAction::triggered,this,&BMserver::modifyItemAction);
    connect(action_copyIt,&QAction::triggered,this,&BMserver::CopyTtemAction);

    book_db.connectdb();

    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);

    model = new QSqlTableModel;
    model->setTable("book");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    ui->tableView->setModel(model);
    ui->tableView->show();
    connect(model,&QSqlTableModel::dataChanged,this,&BMserver::submitModify);

    // ui settings

    justedWindowWidth();

    QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
    move((desktop->width() - this->width())/2, (desktop->height() - this->height())/2);

    ui->bt_MainPage->setIcon(QIcon(":/icon/Home"));
    ui->bt_MainPage->setIconSize(ui->bt_MainPage->size());
}

BMserver::~BMserver()
{
    delete ui;
}


void BMserver::newBookFinished(QStringList strlist)
{
//    qDebug() << "new book arrive";
    int strcount = strlist.count();
    QTime time;
    QSqlRecord record = model->record();
    //QList<QString>::Iterator it = strlist.begin(),itend = strlist.end();

    for(int i=0;i<strcount;i++)
        record.setValue(i,strlist.at(i));
    time.start();
/*  确保数据库里没有isbn相同的书籍这个工作已经被转移给 新建对话框去处理和判断了，这里不再进行数据的校验
    QString isbn = strlist.at(0);
    if(areadyhasSameData(isbn))
    {
        QMessageBox::critical(NULL, "sqlDB add new ERR","there has a same record already!");
        return ;
    }
*/
    if(model->insertRecord(-1,record))
        emit newRecordAdded();
    model->submitAll();
    qDebug() << time.elapsed() << "ms";

#if 0
    int rowNum = model->rowCount();
    model->insertRow(rowNum);   //添加一行
    for(int i=0;i<strlist.count();i++)
    {
        model->setData(model->index(rowNum,i),strlist.at(i));
    }
#endif
}

void BMserver::on_bt_AddNewBook_clicked()
{
    NewBook dlg_Add(this);
    connect(&dlg_Add,&NewBook::editfinished,this,&BMserver::newBookFinished);
    connect(this,&BMserver::newRecordAdded,&dlg_Add,&NewBook::savePost2File);
    dlg_Add.exec();

    disconnect(&dlg_Add,&NewBook::editfinished,this,&BMserver::newBookFinished);
    disconnect(this,&BMserver::newRecordAdded,&dlg_Add,&NewBook::savePost2File);
}

void BMserver::on_tableView_customContextMenuRequested(const QPoint &pos)
{
    qDebug() << pos.x() << "  " << pos.y();
    tableviewPopMenu->addAction(action_delete);
    tableviewPopMenu->addAction(action_modify);
    tableviewPopMenu->addAction(action_copyIt);
    tableviewPopMenu->exec(QCursor::pos());
}

 void BMserver::deleteItemAction()
 {
     qDebug() << " delete action ";
     int curRow = ui->tableView->currentIndex().row();
         //获取选中的行
         model->removeRow(curRow);
         //删除该行
         int ok = QMessageBox::warning(this,tr("删除当前行!"),
                                       tr("你确定""删除当前行吗？"),
                                       QMessageBox::Yes,QMessageBox::No);
         if(ok == QMessageBox::No)
            model->revertAll();//如果不删除，则撤销
         else
             model->submitAll(); //否则提交，在数据库中删除该行

         /* remember to add the code which
          * remove the image resource from img pool
         */
 }

 void BMserver::modifyItemAction()
 {
     qDebug() << " modify  action ";
     /*如果编辑的是isbn列，将现在的参数存起来，之后到编辑完成之后的槽函数中做封面图片的更新*/
     m_isbnBeforeEdit.clear();
     QModelIndex modelIndex = ui->tableView->currentIndex();
     if(modelIndex.column() == 0)
     {
         m_isbnBeforeEdit = modelIndex.data().toString();
         m_isbnBeforeEdit+=tr(".jpg");
     }
     ui->tableView->edit(modelIndex);
 }

 void BMserver::CopyTtemAction()
 {
     qDebug() << " copy item action ";
 }

void BMserver::on_bt_search_clicked()
{
    QString qstr = "colum LIKE '%data%'";
    QString keyword = ui->lineEdit_keyword->text();
    if(keyword.trimmed().isEmpty())
    {
        model->setTable("book");
        model->select();
        return ;
    }
    else
    {
        qstr.replace("colum",ui->comboBox->currentText());
        qstr.replace("data",keyword.trimmed());
        model->setFilter(qstr);
        model->select();
    }
}

/* step 1: 检查是编辑的列（colum）是否需要进行规则检查，如isbn列需要检查新的修改是否满足isbn的命名规则
 * step 2: 如果编辑的是isbn 则需要update图书的封面文件，如果原来有封面文件，则要重命名成新修改的文件名
 * step 3: 提交所做的修改到数据库中
*/
void BMserver::submitModify(const QModelIndex &topLeft,
                            const QModelIndex &bottomRight,
                            const QVector<int> &roles)
{

    if(topLeft.column() == 0)
    {
        QString dirpath = QCoreApplication::applicationDirPath() + tr("/bookPost/");
        QString oldfile = dirpath + m_isbnBeforeEdit;
        QString newfile = dirpath + topLeft.data().toString() + tr(".jpg");

        qDebug() << oldfile << newfile;
        QFileInfo fi(oldfile);
        if(fi.isFile())
        {
            QFile::rename(oldfile, newfile);
        }
    }
    model->submitAll();
}


bool BMserver::areadyhasSameData(QString &isbn)
{
    //  确保数据库里没有isbn相同的书籍
        QString str = "select isbn from book where isbn='@'";
        str.replace("@",isbn);
        QSqlQuery query = model->query();
        if(!query.exec(str))
        {
            qDebug() << "SQLITE ERR:" << "QSqlQery execute Failed!\n";
            return true;
        }
        if(query.next())
            return true;
        else
            return false;
}

void BMserver::justedWindowWidth()
{
    if(book_db.getDBstatus() == DISCONNECTED)
        return ;
    int WinWidth = 172;
    int columCount = ui->tableView->colorCount();
    for(int i=0;i < columCount; i++)
    {
        WinWidth += ui->tableView->columnWidth(i);
    }
    this->resize(WinWidth,this->size().height());
}
